let missionContent = '';

const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws_tasks_list');

ws.onmessage = function(event) {
    try {
        const data = JSON.parse(event.data);
        if (data.user_tasks) {
            renderUserTasks(data.user_tasks);
            missionContent = JSON.stringify(data.user_tasks || '');
        }
    } catch (e) {
        console.error('解析消息失败:', e);
    }
};

function renderUserTasks(userTasks) {
    let container = document.getElementById('user-tasks-container');
    if (!container) {
        container = document.createElement('div');
        container.id = 'user-tasks-container';
        document.body.appendChild(container);
    }
    container.innerHTML = '';
    for (const user in userTasks) {
        const userDiv = document.createElement('div');
        userDiv.className = 'user-block';
        const userTitle = document.createElement('h2');
        userTitle.textContent = `用户：${user}`;
        userDiv.appendChild(userTitle);

        const taskList = document.createElement('ul');
        for (const task of userTasks[user]) {
            const li = document.createElement('li');
            li.innerHTML = `
                <div class="task-header">
                    <span class="task-title">${task.Title}</span>
                    <span class="priority-tag">优先级: ${task.Priority}</span>
                </div>
                <div class="task-desc">${task.Description}</div>
                <div class="task-meta">
                    <span class="status-tag ${task.IsCompleted ? 'done' : 'pending'}">${task.IsCompleted ? '✔ 已完成' : '未完成'}</span>
                    <span class="status-tag ${task.IsObsolete ? 'obsolete' : 'active'}">${task.IsObsolete ? '作废' : '有效'}</span>
                    <span class="date-info">创建: ${task.CreatedDate}</span>
                    <span class="date-info">截止: ${task.DueDate}</span>
                </div>
                `;
            taskList.appendChild(li);
        }
        userDiv.appendChild(taskList);
        container.appendChild(userDiv);
    }
}